/**
 *
 */
package com.ceiec.trace.filter;


import com.ceiec.trace.utils.IpPortContextVO;
import com.ceiec.trace.utils.UrlParser;
import com.ceiec.trace.vo.CurrentRequestMetaData;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.UUID;

/**
 *
 * @author 曹坤亮
 */
//@WebFilter(filterName = "requestInfoMarkFilter", urlPatterns = "/*")
public class RequestTraceFilter implements Filter {



    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("RequestTraceFilter");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String traceId = httpServletRequest.getHeader("traceId");
        if (traceId == null) {
            traceId = UUID.randomUUID().toString();
        }

        //生成请求追求数据
        CurrentRequestMetaData currentRequestMetaData = new CurrentRequestMetaData();
        //设置源主机、源端口
        currentRequestMetaData.setSrcHost(httpServletRequest.getRemoteHost());
        currentRequestMetaData.setSrcPort(String.valueOf(httpServletRequest.getRemotePort()));
        currentRequestMetaData.setRequestUrl(httpServletRequest.getRequestURL().toString());

        //设置该请求的目的主机、端口、上下文
        IpPortContextVO vo = UrlParser.getIpPortContextVO(httpServletRequest.getRequestURL());
        if (vo != null) {
            currentRequestMetaData.setDestHost(vo.getHost());
            currentRequestMetaData.setDestAppName(vo.getContext());
            currentRequestMetaData.setDestPort(vo.getPort());
        }

        currentRequestMetaData.setTraceId(traceId);

        //设置到线程变量中
        RequestHolder.set(currentRequestMetaData);
        chain.doFilter(httpServletRequest, response);
        RequestHolder.remove();
    }

    @Override
    public void destroy() {

    }

}